<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/mine/mineBg.png" mode=""></image>
		</view>
		<cusHeaderVue titleContent="我的" :showBack="false"></cusHeaderVue>
		<scroll-view scroll-y="true"
			:style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`,height: `calc(100vh - ${scrollerHeight} - 90rpx)`}">
			<view class="contBox" style="min-height: 100%;">
				<view class="contHeader">
					<view class="contPhoto">
						<image :src="userInfo.avatar" mode=""></image>
					</view>
					<view class="contText">
						<view class="contName">
							{{userInfo.nickname}}
						</view>
						<view class="contGw">
							岗位：<text>{{userInfo.userType == 0 ? '动销员' : '管理员'}}</text>
						</view>
					</view>
				</view>

		
				
				<!-- 管理员 -->
				<view class="zhibiao">
					<view class="zhibiaoTit">
						本月指标
					</view>
					<view class="zhibiaoCont">
					<view class="zhibiaoContLi" @click="toUrl('/pages/mine/myTask')">
						<image src="/static/mine/dbrw.png" mode=""></image>
						<view class="zhibiaoNum" style="color: #FF3D3D;">
							{{myData.dbNum}} <text style="color: #FF3D3D;">个</text>
						</view>
							
						<view class="zhibiaoName">
							待办任务
						</view>
					</view>
					<view v-if="userInfo.userType != 1" @click="toUrl('/pages/index/checkInStatistics')" class="zhibiaoContLi">
						<image src="/static/mine/dkcs.png" mode=""></image>
						<view class="zhibiaoNum">
							{{myData.dkNum}}<text>次</text>
						</view>
						<view class="zhibiaoName">
							打卡次数
						</view>
					</view>

					<view v-else class="zhibiaoContLi" @click="toUrl('/pages/index/salesRepresentative?mode=month')" >
					<image src="/static/mine/dkcs.png" mode=""></image>
						<view class="zhibiaoNum">
							{{myData.dkNum}} 次
						</view>
						<view class="zhibiaoName">
							打卡次数
						</view>
						
					</view>
					<!-- 管理员显示指标完成率 -->
					<view v-if="userInfo.userType == 1" class="zhibiaoContLi">
						<image src="/static/mine/mendian.png" mode=""></image>
						<view class="zhibiaoNum">
							{{myData.wclStr}}
						</view>
						<view class="zhibiaoName">
							指标完成率
						</view>
					</view>

					<!-- 动销员显示未打卡门店 -->
					<view @click="toUrl('/pages/mine/didNotClockIn')" v-else-if="userInfo.userType == 0" class="zhibiaoContLi">
						<image src="/static/mine/mendian.png" mode=""></image>
						<view class="zhibiaoNum">
							{{myData.wdkNum}}
						</view>
						<view class="zhibiaoName">
							未打卡门店
						</view>
					</view>
						
					</view>
				</view>
				
				<!-- 消息订阅授权按钮 -->
				<view v-if="!isSubscribed" style="width: 100%;padding: 14rpx 22rpx;box-sizing: border-box;">
					<view class="btnBox" @click="requestMessageSubscribe">
						<view class="subscribe-btn">
							开启消息通知
						</view>
					</view>
				</view>

				<view class="serveList">
					<!-- 消息订阅状态 -->
					<view class="serveLi">
						<view class="serveLeft">
							消息通知
						</view>
						<view class="serveRight">
							<view class="serveRightText" :style="{ color: isSubscribed ? '#4CAF50' : '#FF3D3D' }">
								{{ isSubscribed ? '已开启' : '未开启' }}
							</view>
							<!-- <u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon> -->
						</view>
					</view>
					<!-- 动销员菜单项 -->
					<view v-if="userInfo.userType == 0">
						<view class="serveLi"  @click="toUrl('/pages/mine/mySupplies')">
							<view class="serveLeft">
								我的物料
							</view>
							<view class="serveRight">
								<u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon>
							</view>
						</view>
						<view class="serveLi"  @click="toUrl('/pages/mine/myTask')">
							<view class="serveLeft" >
								我的任务
							</view>
							<view class="serveRight">
								<view class="serveRightText">
									累计完成<text>{{myData.taskNum || 0}}</text>次
								</view>
								<u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon>
							</view>
						</view>
						<view class="serveLi"  @click="toUrl('/pages/mine/performanceAssessment')">
							<view class="serveLeft" >
								我的考核
							</view>	
							<view class="serveRight">
								<view class="serveRightText" style="color: #49443c;">
									上月评分：{{myData.mouthScore}}分
								</view>
								<u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon>
							</view>
						</view>
					</view>

					<!-- 管理员菜单项 -->
					<view v-else-if="userInfo.userType == 1">
						<view class="serveLi" @click="toUrl('/pages/mine/mySalesperson')">
							<view class="serveLeft">
								我的动销员
							</view>
							<view class="serveRight">
								<view class="serveRightText">
									<text>{{myData.dxNum || 0}}</text>人
								</view>
								<u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon>
							</view>
						</view>
						<view class="serveLi"  @click="toUrl('/pages/mine/myTask')">
							<view class="serveLeft">
								我的任务
							</view>
							<view class="serveRight">
								<view class="serveRightText">
									累计下发<text>{{myData.taskNum}}</text>次
								</view>
								<u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon>
							</view>
						</view>
						
						<view class="serveLi"  @click="toUrl('/pages/mine/performanceAssessmentAdmin')">
							<view class="serveLeft">
								绩效考核
							</view>
							<view class="serveRight">
								<view class="serveRightText" style="color: #FF3D3D;">
									{{myData.dpf}}人待评分
								</view>
								<u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon>
							</view>
						</view>
					</view>

					<!-- 通用菜单项 -->
					<view class="serveLi" @click="toUrl('/pages/mine/changePassword')">
						<view class="serveLeft">
							修改密码
						</view>
						<view class="serveRight">
							<u-icon name="arrow-right" color="#AFAFB0" size="15"></u-icon>
						</view>
					</view>
				</view>
			
			
			<!-- 退出登录按钮 -->
			<view style="width: 100%;">
				<view class="btnBox" @click="logout()">
					<view class="btnLi">
						退出登录
					</view>
				</view>
			</view>

		</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import { ref, computed } from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import { requestSubscribe, SUBSCRIBE_TYPES, getSubscribeStatus } from '@/utils/subscribeMessage.js';
	
	import {
		authLogin,
		updateGuestPassword,
		verifyGesturePassword,
		updateUserPassword,
		GETUserInfo,
		getMyData,
		GETUnreadNotifyList
	} from '@/api/interface.js';
	
	
	const scrollerHeight = ref('');
	
	const userInfo = ref({});
const myData = ref({});
// 订阅消息相关状态
const isSubscribed = ref(false);

// 计算属性：获取所有订阅模板的订阅状态
const messageStatus = computed(() => {
  const unreadNoticeTemplate = '9yjsEEOp2gnaWJTR6MqhonTNrrK88GFEhMnvUEx6h4s';
  const approvalProgressTemplate = 'JNfZ9hgoxm6-y2UVFiiJ0FJYBYH3nSGPGFS_PsAtwwk';
  
  const unreadStatus = getSubscribeStatus(unreadNoticeTemplate).isSubscribed;
  const approvalStatus = getSubscribeStatus(approvalProgressTemplate).isSubscribed;
  
  return {
    canReceive: unreadStatus || approvalStatus,
    unreadNotice: unreadStatus,
    approvalProgress: approvalStatus
  };
});

// 请求消息订阅权限
const requestMessageSubscribe = () => {
  requestSubscribe([SUBSCRIBE_TYPES.UNREAD_NOTICE, SUBSCRIBE_TYPES.APPROVAL_PROGRESS])
    .then(res => {
      // 检查是否有订阅成功的模板
      const hasAccepted = Object.values(res).some(status => status === 'accept');
      
      // 订阅成功后立即设置isSubscribed为true，确保按钮立即隐藏
      if (hasAccepted) {
        isSubscribed.value = true;
        uni.showToast({ title: '消息订阅成功', icon: 'success' });
      }
      
      // 确保存储已更新并同步状态
      setTimeout(() => {
        checkSubscribeStatus();
      }, 0);
    })
    .catch(err => {
      console.error('订阅消息失败:', err);
      // 显示更友好的提示，告知用户授权成功并引导再次点击
      uni.showToast({ 
        title: '授权微信openid成功，请再次点击订阅消息', 
        icon: 'none',
        duration: 2000
      });
    });
};

// 检查消息订阅状态
const checkSubscribeStatus = (initial = false) => {
  // 强制重新获取状态
  const unreadNoticeTemplate = '9yjsEEOp2gnaWJTR6MqhonTNrrK88GFEhMnvUEx6h4s';
  const approvalProgressTemplate = 'JNfZ9hgoxm6-y2UVFiiJ0FJYBYH3nSGPGFS_PsAtwwk';
  
  const unreadStatus = getSubscribeStatus(unreadNoticeTemplate).isSubscribed;
  const approvalStatus = getSubscribeStatus(approvalProgressTemplate).isSubscribed;
  
  const canReceive = unreadStatus || approvalStatus;
  
  // 总是更新isSubscribed状态，确保UI与实际状态一致
  isSubscribed.value = canReceive;
  
  console.log('消息订阅状态:', { canReceive, unreadStatus, approvalStatus });
};
	
	onShow(() => {
	getUserInfo();
	checkSubscribeStatus(true);
});
	
	// 点击 marker
	const getUserInfo = (e) => {
		
		getMyData({}).then(res => {
			console.log(res.data)
			myData.value = res.data
			userInfo.value = res.data.userInfo
		}).catch(err => {
			
		});
		
	}
	
	// 退出登录
	const logout = () => {
		uni.showModal({
			title: '退出登录',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					// 清理本地缓存
					uni.clearStorage();
					// 跳转到登录页面
					uni.reLaunch({
						url: "/pages/index/login"
					});
				}
			}
		});
	}
	
	
	
	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
			}
		});
	}

	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	}
	onLoad(() => {

getBarHeight();
	// 页面加载时检查订阅状态
	checkSubscribeStatus(true);
})
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 100%;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.contBox {
		padding: 22rpx;
		box-sizing: border-box;
		padding-bottom: calc(env(safe-area-inset-bottom) + 101rpx);
		.contHeader{
			display: flex;
			align-items: center;
			.contPhoto{
				width: 95.55rpx;
				height: 95.55rpx;
				background: #f8c79a;
				border-radius: 50%;
				image{
					width:100%;
					height: 100%;
					border-radius: 50%;
				}
			}
			.contText{
				margin-left: 19rpx;
				.contName{
					font-weight: 500;
					font-size: 33.33rpx;
					color: #1C2027;
				}
				.contGw{
					 color: #5a5964;
					 font-weight: 400;
					 font-size: 24.36rpx;
					text{
						 color: #b76712;
						 font-weight: 400;
						 font-size: 24.36rpx;
					}
				}
			}
		}
		.zhibiao{
			padding: 35rpx 27rpx;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			box-sizing: border-box;
			margin-top: 18rpx;
			.zhibiaoTit{
				font-weight: 500;
				font-size: 33.33rpx;
				color: #000000;
			}
			.zhibiaoCont{
				display: grid;
				grid-template-columns: 1fr 1fr 1fr;
				width: 100%;
				border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
				background: #fff9f2;
				padding: 27rpx 0;
				box-sizing: border-box;
				margin-top: 28rpx;
				.zhibiaoContLi{
					display: flex;
					align-items: center;
					justify-content: center;
					flex-direction: column;
					image{
						width: 32.69rpx;
						height: 31.41rpx;
					}
					.zhibiaoNum{
						font-size: 37.18rpx;
						font-weight: 400;
						color: #222222;
						margin-top: 15rpx;
						text{
							font-size: 23.08rpx;
							font-weight: 400;
							color: #222222;
						}
					}
					.zhibiaoName{
						font-size: 25.64rpx;
						font-weight: 400;
						color: #7F8494;
					}
				}
			}
		}
		.serveList{
			margin-top: 23rpx;
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			.serveLi{
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 35rpx 32rpx;
				box-sizing: border-box;
				.serveLeft{
					color: #1c2027;
					 font-weight: 500;
					 font-size: 32.05rpx;
				}
				.serveRight{
					display: flex;
					align-items: center;
					.serveRightText{
						color: #afafb0;
						 font-weight: 400;
						 font-size: 28.21rpx;
						text{
							color: #f79f31;
							 font-weight: 400;
							 font-size: 28.21rpx;
							 margin: 0 10rpx;
						}
					}
				}
			}
		}
	}

	.btnBox {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		padding: 40rpx 35rpx;
		box-sizing: border-box;
		background: transparent;
		// margin-top: 30rpx;

		.btnLi {
			height: 88rpx;
			border-radius: 44rpx;
			background: linear-gradient(90deg, #feaf38, #f98434);
			box-shadow: 0 4rpx 8rpx 0 #f984344d;
			color: #ffffff;
			width: 100%;
			max-width: 512.82rpx;
			font-size: 32.05rpx;
			font-weight: 500;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.subscribe-btn {
			height: 88rpx;
			border-radius: 44rpx;
			background: #ffffff;
			border: 2rpx solid #4CAF50;
			color: #4CAF50;
			width: 100%;
			max-width: 512.82rpx;
			font-size: 32.05rpx;
			font-weight: 500;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
</style>